import type { RouteRecordStringComponent } from '@vben/types';

import { requestClient } from '#/api/request';

/**
 * 获取用户所有菜单
 */
// export async function getAllMenusApi() {
//   return requestClient.get<RouteRecordStringComponent[]>('/menu/all');
// }

// CHANGE0000
export async function getAllMenusApi() {
  console.log('getAllMenusApi');
  return requestClient.get<RouteRecordStringComponent[]>('/current/user/menu');
}

// 递归处理菜单数据

interface MenuItem {
  menuId: string;
  menuName: string;
  parentId: string;
  path: string;
  menuLayout: string;
  priority: number;
  menuCode: string;
  icon: string;
}

interface TransformedMenu {
  name: string;
  path: string;
  component: string;
  meta: {
    order: number;
    title: string;
    icon: string;
    affixTab: boolean;
  };
  children?: TransformedMenu[];
}
export function transformMenuData(
  menuData: MenuItem[],
): RouteRecordStringComponent[] {
  // 创建一个映射表，方便通过 menuId 查找菜单项
  const menuMap = new Map<string, MenuItem>();
  menuData.forEach((menu) => {
    menuMap.set(menu.menuId, menu);
  });

  // 递归构建菜单树
  function buildTree(menu: MenuItem): TransformedMenu {
    const children = menuData.filter((item) => item.parentId === menu.menuId);
    return {
      name: menu.menuName,
      path: menu.path,
      component:
        menu.menuLayout === 'LAYOUT'
          ? 'BasicLayout'
          : menu.menuLayout.replace('views/', '').replace('.vue', ''),
      meta: {
        order: menu.priority,
        title: menu.menuName,
        icon: menu.icon,
        affixTab: menu.menuCode === 'dashboard', // 示例：只有 dashboard 固定标签
      },
      children:
        children.length > 0
          ? children.map((child) => buildTree(child))
          : undefined,
    };
  }

  // 找到根节点（parentId 为 '0' 的菜单项）
  const rootMenus = menuData.filter((menu) => menu.parentId === '0');

  // 构建最终的菜单树
  const dashboardMenus = rootMenus.map((rootMenu) => buildTree(rootMenu));

  return dashboardMenus;
}
